package com.woniuxy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.common.ConstantData;
import com.woniuxy.common.RedisKey;
import com.woniuxy.controller.form.FoodVarietyInsertForm;
import com.woniuxy.controller.form.FoodVarietySearchForm;
import com.woniuxy.controller.form.FoodVarietyUpdateForm;
import com.woniuxy.controller.form.FoodVarietyUpdateStatusForm;
import com.woniuxy.entity.FoodType;
import com.woniuxy.entity.FoodVariety;
import com.woniuxy.dao.FoodVarietyMapper;
import com.woniuxy.entity.StoreInfo;
import com.woniuxy.exception.foodVariety.FoodVarietyException;
import com.woniuxy.exception.foodVariety.FoodVarietyExceptionCode;
import com.woniuxy.service.FoodTypeService;
import com.woniuxy.service.FoodVarietyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.StoreInfoService;
import com.woniuxy.service.dto.FoodForEsDto;
import com.woniuxy.service.dto.FoodVarietyDto;
import com.woniuxy.service.dto.StoreInfoForEsDto;
import com.woniuxy.service.dto.WoniuPageDto;
import com.woniuxy.util.EsUtil;
import com.woniuxy.util.RedisUtil;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜品 服务实现类
 * </p>
 *
 * @author zz
 * @since 2023年06月13日
 */
@Service
public class FoodVarietyServiceImpl extends ServiceImpl<FoodVarietyMapper, FoodVariety> implements FoodVarietyService {

    @Autowired
    private StoreInfoService storeInfoService;
    @Autowired
    private FoodVarietyMapper mapper;
    @Autowired
    private FoodTypeService foodTypeService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ElasticsearchRestTemplate template;
    @Autowired
    private EsUtil esUtil;




    @Override
    @Transactional
    public FoodVariety insert(FoodVarietyInsertForm form, Integer accountId) throws Exception {
        StoreInfo storeInfo = storeInfoService.getOne(new QueryWrapper<StoreInfo>().eq("accountId", accountId));
        if(storeInfo.getStatus() == ConstantData.STORE_INFO_STATUS_FREEZE ||storeInfo.getDeleteFlag()==ConstantData.STATE_DEL){
            throw new FoodVarietyException(FoodVarietyExceptionCode.STORE_STATUS_DISABLE);
        }
        FoodVariety foodVariety = mapper.selectOne(new QueryWrapper<FoodVariety>().eq("foodName", form.getFoodName()).eq("storeId",storeInfo.getId()));
        if(foodVariety!=null){
            throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_IS_EXIST);
        }
        FoodVariety food = BeanUtil.toBean(form, FoodVariety.class);
        food.setDeleted(ConstantData.STATE_NORMAL);
        food.setStoreId(storeInfo.getId());
        food.setStoreName(storeInfo.getStoreName());
        food.setState(ConstantData.FOOD_STATUS_USABLE);
        FoodType foodType = foodTypeService.getById(form.getTypeId());
        if(foodType!=null){
            //菜品类别异常
        }
        //菜品类别不是叶子 或者叶子类型被禁用
//        if(){
//
//        }
        food.setTypeName(foodType.getTypeName());
        food.setSortNum(0);
        //新增数据库
        mapper.insert(food);
        System.out.println(food.getId());
        redisUtil.zadd(RedisKey.getStoreFoods(storeInfo.getId().toString()),RedisKey.getFoodInfoByFoodId(food.getId().toString()),0);
        //新增Es
        FoodVariety newFood = mapper.selectById(food.getId());
        FoodForEsDto foodForEsDto = BeanUtil.toBean(newFood, FoodForEsDto.class);
        StoreInfoForEsDto storeInfoForEsDto = esUtil.findOneStore(storeInfo.getId());
        List<FoodForEsDto> list = storeInfoForEsDto.getFood();
        if(list==null){
            list = new ArrayList<>();
        }
        list.add(foodForEsDto);
        storeInfoForEsDto.setFood(list);
        template.save(storeInfoForEsDto);
        return food;
    }

    @Override
    public void updateStatus(FoodVarietyUpdateStatusForm form, Integer accountId) throws Exception {
        StoreInfo storeInfo = storeInfoService.getOne(new QueryWrapper<StoreInfo>().eq("accountId", accountId));
        if(storeInfo.getStatus() == ConstantData.STORE_INFO_STATUS_FREEZE ||storeInfo.getDeleteFlag()==ConstantData.STATE_DEL){
            throw new FoodVarietyException(FoodVarietyExceptionCode.STORE_STATUS_DISABLE);
        }
        FoodVariety foodVariety = mapper.selectById(form.getId());
        if(form.getDeleted()!=null){ //删除菜品
            if(foodVariety.getDeleted()==ConstantData.STATE_DEL){
                throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_IS_DEL);
            }
            //改数据库状态 同步redis
            foodVariety.setDeleted(ConstantData.STATE_DEL);
            this.saveOrUpdate(foodVariety);
            redisUtil.zremove(RedisKey.getStoreFoods(storeInfo.getId().toString()),RedisKey.getFoodInfoByFoodId(foodVariety.getId().toString()));
            //删除es
            StoreInfoForEsDto storeInfoForEsDto = esUtil.findOneStore(storeInfo.getId());
            List<FoodForEsDto> foods = storeInfoForEsDto.getFood();
            FoodForEsDto foodForEsDto = BeanUtil.toBean(foodVariety, FoodForEsDto.class);
            foods.remove(foodForEsDto);
            storeInfoForEsDto.setFood(foods);
            template.save(storeInfoForEsDto);
        }
        if(form.getState()!=null){//上下架
            if(foodVariety.getState()==ConstantData.FOOD_STATUS_USABLE && form.getState()==foodVariety.getState()){
                throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_IS_USABLE);
            }
            if(foodVariety.getState()==ConstantData.FOOD_STATUS_DISABLE && form.getState()==foodVariety.getState()){
                throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_IS_DISABLE);
            }
            if(foodVariety.getDeleted()==ConstantData.STATE_DEL){
                throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_IS_DEL);
            }
            FoodType foodType = foodTypeService.getById(foodVariety.getTypeId());
            if(foodType.getTypeState()!=ConstantData.FOOD_TYPE_STATUS_NORMAL){
                throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_TYPE_IS_DISABLE);
            }
            foodVariety.setState(form.getState());
            this.saveOrUpdate(foodVariety);
        }

    }

    @Override
    public WoniuPageDto<FoodVarietyDto> searchByCondition(FoodVarietySearchForm form, Integer accountId) {
        StoreInfo storeInfo = storeInfoService.getOne(new QueryWrapper<StoreInfo>().eq("accountId", accountId));
        Page<FoodVariety> page = new Page<>(form.getCurrent() == null ? 1 : form.getCurrent(), form.getSize() == null ? 20 : form.getSize());
        QueryWrapper<FoodVariety> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted",ConstantData.STATE_NORMAL).eq("storeId",storeInfo.getId());
        if( form.getSortNum()!=null){
            wrapper.eq("sortNum",form.getSortNum());
        }
        if(form.getFoodName()!=null && !form.getFoodName().equals("")) {
            wrapper.eq("foodName",form.getFoodName());
        }
        if(form.getEndPrice()!=null){
            wrapper.le("price",Double.parseDouble(form.getEndPrice().toString()));
        }
        if(form.getStartPrice()!=null){
            wrapper.ge("price",Double.parseDouble(form.getStartPrice().toString()));
        }
        if(form.getTypeId()!=null){
            wrapper.eq("typeId",form.getTypeId());
        }
        if(form.getState()!=null){
            wrapper.eq("state",form.getState());
        }
        mapper.selectPage(page, wrapper);
//        if(page.getRecords().size()==0 || page.getRecords()==null){
//            throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_IS_NULL);
//        }
        ArrayList<FoodVarietyDto> dtos = new ArrayList<>();
        for (FoodVariety foodVariety : page.getRecords()) {
            FoodVarietyDto dto = BeanUtil.toBean(foodVariety, FoodVarietyDto.class);
            if(foodVariety.getSortNum()==ConstantData.FOOD_IS_SPECIALTY){
                dto.setSpecialty("招牌菜");
            }else{
                dto.setSpecialty("普通菜品");
            }
            if(foodVariety.getState()==ConstantData.FOOD_STATUS_USABLE){
                dto.setStateName("上架中");
            }else{
                dto.setStateName("下架中");
            }
            dtos.add(dto);
        }
        WoniuPageDto woniuPageDto = BeanUtil.toBean(page, WoniuPageDto.class);
        woniuPageDto.setList(dtos);
        return woniuPageDto;
    }

    @Override
    public void updateMessage(FoodVarietyUpdateForm form, Integer accountId) {
        StoreInfo storeInfo = storeInfoService.getOne(new QueryWrapper<StoreInfo>().eq("accountId", accountId));
        FoodVariety foodVariety = mapper.selectById(form.getId());
        if(foodVariety==null){
            throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_IS_NULL);
        }
        if(foodVariety.getDeleted()==ConstantData.STATE_DEL){
            throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_IS_DEL);
        }
        FoodVariety newFood = BeanUtil.toBean(form, FoodVariety.class);

        FoodType foodType = foodTypeService.getById(form.getTypeId());
        if(foodType==null || foodType.getTypeState()!=ConstantData.FOOD_TYPE_STATUS_NORMAL){
            throw new FoodVarietyException(FoodVarietyExceptionCode.FOOD_TYPE_IS_DISABLE);
        }
        this.saveOrUpdate(newFood);
    }
}
